//
//  PayViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/12.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "PayViewController.h"

@interface PayViewController ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UIAlertViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView*tableView;

@property(nonatomic,strong)UITextField *CVVTextfield;
@property(nonatomic,strong)UITextField *numberTextField;

@property(nonatomic,strong)UIButton *monthButton;
@property(nonatomic,strong)UIButton *yearButton;

@property(nonatomic,strong)NSArray *monthArray;
@property(nonatomic,strong)NSArray *yearArray;

@property(nonatomic,strong)UIPickerView *monthPickView;
@property(nonatomic,strong)UIPickerView *YearPickView;
@property(nonatomic,strong)NSString *monthStr;
@property(nonatomic,strong)NSString *yearStr;

@property(nonatomic,assign)BOOL canSave;    //判断是否符合

@end

@implementation PayViewController

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,ACTUAL_HEIGHT(70), KScreenWidth, ACTUAL_HEIGHT(450)) style:UITableViewStyleGrouped];
        _tableView.delegate  =self;
        _tableView.dataSource=self;
        //_tableView.backgroundColor = [UIColor whiteColor];
    }
    return _tableView;
}

- (void)viewDidLoad {
    self.numberTextField.delegate = self;
    self.CVVTextfield.delegate = self;
    self.view.backgroundColor=[UIColor whiteColor];
    [super viewDidLoad];
    _canSave=NO;
    [self getDatas];
    [self creatPickerView];
    [self makeNaviButton];
    [self makeView];
    
    [self.view addSubview:self.tableView];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
    [self.view bringSubviewToFront:_monthPickView];
    [self.view bringSubviewToFront:_YearPickView];
 
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.numberTextField) {
        // 四位加一个空格
        if ([string isEqualToString:@""]) { // 删除字符
            if ((textField.text.length - 2) % 5 == 0) {
                textField.text = [textField.text substringToIndex:textField.text.length - 1];
            }
            return YES;
        } else {
            if (textField.text.length % 5 == 0) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
        return YES;
    }
    return YES;
}


-(void)makeView{
    UIButton *payNowButton=[[UIButton alloc]initWithFrame:CGRectMake( (KScreenWidth-ACTUAL_WIDTH(ACTUAL_WIDTH(330)))/2, ACTUAL_HEIGHT(515), ACTUAL_WIDTH(ACTUAL_WIDTH(330)), ACTUAL_HEIGHT(50))];
    payNowButton.backgroundColor=[UIColor blackColor];
    [payNowButton addTarget:self action:@selector(finishPayNow:) forControlEvents:UIControlEventTouchUpInside];
    [payNowButton setTitle:@"PAY NOW" forState:0];
    payNowButton.tag=666;
    [self.view addSubview:payNowButton];
    
    UIImageView *bottomImageView=[[UIImageView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(20), KScreenHeight-ACTUAL_HEIGHT(87), ACTUAL_WIDTH(67), ACTUAL_HEIGHT(67))];
    [bottomImageView setImage:[UIImage imageNamed:@"img_guarantee"]];
    [self.view addSubview:bottomImageView];
    
    UILabel *bottomLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(90), ACTUAL_HEIGHT(595), ACTUAL_WIDTH(270), ACTUAL_HEIGHT(40))];
//    bottomLabel.backgroundColor=[UIColor yellowColor];
    bottomLabel.numberOfLines=2;
    bottomLabel.font=[UIFont systemFontOfSize:12];
    bottomLabel.text=@"We will not save your credit information trusted by over one million shoppers in 50 countries";
    [self.view addSubview:bottomLabel];
    
}

-(void)getDatas{
    _monthArray=@[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    
    _yearArray=@[@"2016",@"2017",@"2018",@"2019",@"2020",@"2021",@"2022",@"2023",@"2024",@"2025",@"2026",@"2027",@"2028",@"2029",@"2030",@"2031"];
}

-(void)makeNaviButton{
    
    self.title=@"Payment Info";
    
    UIButton *forkButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(320), 0, ACTUAL_WIDTH(30), ACTUAL_HEIGHT(30))];
    [forkButton setImage:[UIImage imageNamed:@"nav_close"] forState:0];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    //    forkButton.backgroundColor=[UIColor yellowColor];
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    
//    forkButton.backgroundColor=[UIColor yellowColor];
    [forkButton addTarget:self action:@selector(comeBackToRoot) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*item1 = [[UIBarButtonItem alloc]initWithCustomView:forkButton];
    UIBarButtonItem*item= [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem=item;
    self.navigationItem.rightBarButtonItem=item1;
}

#pragma mark --------- tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(section == 0) {
        return ACTUAL_HEIGHT(35);
    }
    
    return ACTUAL_HEIGHT(70);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return ACTUAL_HEIGHT(15);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ACTUAL_HEIGHT(310);
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"celll"];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"celll"];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }

    
    if (indexPath.section==1){
        
        //CVV2/CVC2
         UILabel *nameLabel=[cell viewWithTag:01];
         if (!nameLabel) {
             nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(110), ACTUAL_WIDTH(200), ACTUAL_HEIGHT(30))];
             nameLabel.text=@"CVV2/CVC2:";
             nameLabel.font = FONT_SYSTEM_28;
             nameLabel.tag=01;
             [cell addSubview:nameLabel];
         }
         
         UILabel *BGLabel1=[cell viewWithTag:02];
         if (!BGLabel1) {
             BGLabel1=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(150), ACTUAL_WIDTH(355), ACTUAL_HEIGHT(50))];
             BGLabel1.tag=02;
             [cell addSubview:BGLabel1];
         }
         BGLabel1.layer.borderColor = [RGBCOLOR(202, 203, 204, 1)CGColor];
         BGLabel1.layer.borderWidth = 1;
        
        
         _CVVTextfield=[cell viewWithTag:03];
         if (!_CVVTextfield) {
             _CVVTextfield=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(20), ACTUAL_HEIGHT(155), ACTUAL_WIDTH(340), ACTUAL_HEIGHT(40))];
             _CVVTextfield.tag=03;
             _CVVTextfield.keyboardType=UIKeyboardTypeNumberPad;
             [cell addSubview:_CVVTextfield];
         }
        _CVVTextfield.placeholder=@"CVV2/CVC2";
        
        [_CVVTextfield addTarget:self action:@selector(MimitTextFieldLength:)
                   forControlEvents:UIControlEventEditingChanged];

        
        
        //Card Number
         UILabel *BGLabel3=[cell viewWithTag:04];
         if (!BGLabel3) {
             BGLabel3=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(50), ACTUAL_WIDTH(355), ACTUAL_HEIGHT(50))];
             BGLabel3.tag=04;
             [cell addSubview:BGLabel3];
         }
         BGLabel3.layer.borderColor = [RGBCOLOR(202, 203, 204, 1)CGColor];
         BGLabel3.layer.borderWidth = 1;
         
         UILabel *numberLabel=[cell viewWithTag:05];
         if (!numberLabel) {
             UILabel *numberLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(10), ACTUAL_WIDTH(200), ACTUAL_HEIGHT(30))];
             numberLabel.text=@"Card Number";
             numberLabel.font = FONT_SYSTEM_28;
             numberLabel.tag=05;
             [cell addSubview:numberLabel];
         }
        
         _numberTextField=[cell viewWithTag:06];
         if (!_numberTextField) {
             _numberTextField=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(20), ACTUAL_HEIGHT(55), ACTUAL_WIDTH(340), ACTUAL_HEIGHT(40))];
            _numberTextField.tag=06;
             _numberTextField.keyboardType=UIKeyboardTypeNumberPad;
           [cell addSubview:_numberTextField];
         }
        _numberTextField.placeholder=@"Card Number";

        [_numberTextField addTarget:self action:@selector(LimitTextFieldLength:)
                       forControlEvents:UIControlEventEditingChanged];
        _numberTextField.delegate = self;
    
        
        
        //month
         UILabel *dateLabel=[cell viewWithTag:07];
         if (!dateLabel) {
             dateLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(210), ACTUAL_WIDTH(170), ACTUAL_HEIGHT(30))];
             dateLabel.tag=07;
             [cell addSubview:dateLabel];
         }
        dateLabel.text=@"Month";
        dateLabel.font = FONT_SYSTEM_28;
        
        _monthButton=[cell viewWithTag:13];
        if (!_monthButton) {
            _monthButton =[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(10), ACTUAL_HEIGHT(250), ACTUAL_WIDTH(170), ACTUAL_HEIGHT(50))];
            _monthButton.tag=13;
            [_monthButton addTarget:self action:@selector(selectMonth) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:_monthButton];
        }
        _monthButton.layer.borderColor = [RGBCOLOR(202, 203, 204, 1)CGColor];
        _monthButton.layer.borderWidth = 1;
        [_monthButton setTitleColor:[UIColor blackColor] forState:0];
        _monthButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _monthButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        
        
        
        //year
         UILabel *securityLabel=[cell viewWithTag:10];
         if (!securityLabel) {
             securityLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(190), ACTUAL_HEIGHT(210), ACTUAL_WIDTH(170), ACTUAL_HEIGHT(30))];
             securityLabel.tag=10;
           [cell addSubview:securityLabel];
         }
        securityLabel.text=@"Year";
        securityLabel.font = FONT_SYSTEM_28;
        
         _yearButton=[cell viewWithTag:14];
         if (!_yearButton) {
             _yearButton =[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(190), ACTUAL_HEIGHT(250), ACTUAL_WIDTH(170), ACTUAL_HEIGHT(50))];
             _yearButton.tag=14;
             [_yearButton addTarget:self action:@selector(selectYear) forControlEvents:UIControlEventTouchUpInside];
             [_yearButton setTitleColor:[UIColor blackColor] forState:0];
             _yearButton.layer.borderColor = [RGBCOLOR(202, 203, 204, 1)CGColor];
             _yearButton.layer.borderWidth = 1;
             _yearButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
             _yearButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

             [cell addSubview:_yearButton];
         }
}
    
    return cell;
}
-(void) LimitTextFieldLength:(id)sender{
    
    if (self.numberTextField.text.length>20) {
        
        
        self.numberTextField.text = [self.numberTextField.text substringToIndex:20];
        
        NSLog(@" _Textfield.text  %@ ",self.numberTextField.text );
        
        
        
    }else if(self.numberTextField.text.length > 19) {
            [self.numberTextField resignFirstResponder];
            
        }

    
    
}
-(void) MimitTextFieldLength:(id)sender{
    
    if (self.CVVTextfield.text.length > 3) {
        
        
        self.CVVTextfield.text = [self.CVVTextfield.text substringToIndex:3];
        
        NSLog(@" _Textfield.text  %@ ",self.CVVTextfield.text );
        
        
        
    }else if(self.CVVTextfield.text.length > 2) {
        [self.CVVTextfield resignFirstResponder];

    }
    
    
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if(section == 0){
    
        UIView * BGView = [[UIView alloc] init];
        BGView.frame = CGRectMake(0, 0, KScreenWidth, ACTUAL_HEIGHT(20));
        BGView.backgroundColor=[UIColor whiteColor];
        
        
        //order total
        UILabel * orderLabel2 = [[UILabel alloc] init];
        orderLabel2.frame = CGRectMake( 10, 10, KScreenWidth/2, ACTUAL_HEIGHT(20));
        orderLabel2.text =@"Order Total";
        [BGView addSubview:orderLabel2];
        
        UILabel * orderLabel3 = [[UILabel alloc] init];
        orderLabel3.frame = CGRectMake( KScreenWidth/2, 10, KScreenWidth/2-10, ACTUAL_HEIGHT(20));
        orderLabel3.text =self.allPrice;
        orderLabel3.textColor = [UIColor redColor];
        orderLabel3.textAlignment = NSTextAlignmentRight;
        [BGView addSubview:orderLabel3];
        
        return BGView;
    }
    
    
    if (section==1) {
        UIView *BGView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, ACTUAL_HEIGHT(70))];
        BGView.backgroundColor=[UIColor whiteColor];
        NSArray *array=@[@"img_visa",@"img_mastercard",@"img_visa_debit",@"img_mastercard_debit",@"img_jcb"];
        for (int i=0; i<5; i++) {

            UIImageView *payImageView=[[UIImageView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(30)+ACTUAL_WIDTH(70)*i, ACTUAL_HEIGHT(20), ACTUAL_WIDTH(40), ACTUAL_HEIGHT(25))];
            [payImageView setImage:[UIImage imageNamed:array[i]]];
            [BGView addSubview:payImageView];
            
        }
        
        return BGView;
    }
    return nil;
}

#pragma mark - 返回事件

-(void)comeBackToRoot{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[SlideNavigationController sharedInstance].rightMenu viewWillAppear:YES];
    
}

-(void)comeBack{
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@""
                                                         message:@"Payment not finished, are you sure you want to go back?"
                                                        delegate:self
                                               cancelButtonTitle:@"NO"
                                               otherButtonTitles:@"YES", nil];
    [alertView show];
}
-(void)creatPickerView{
    _monthPickView=[[UIPickerView alloc]initWithFrame:CGRectMake(0, KScreenHeight-ACTUAL_HEIGHT(200),KScreenWidth, ACTUAL_HEIGHT(200))];
    _monthPickView.delegate=self;
    _monthPickView.backgroundColor = [UIColor whiteColor];
    _monthPickView.hidden = YES;
    [self.view addSubview:_monthPickView];
    _YearPickView=[[UIPickerView alloc]initWithFrame:CGRectMake(0, KScreenHeight-ACTUAL_HEIGHT(200),KScreenWidth, ACTUAL_HEIGHT(200))];
    _YearPickView.delegate=self;
    _YearPickView.hidden = YES;
    _YearPickView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_YearPickView];

}

#pragma mark - 选择Month的PickView
-(void)selectMonth{

    _monthPickView.hidden = NO;
    _YearPickView.hidden = YES;
}

//选择Year的PickView
-(void)selectYear{

    _monthPickView.hidden = YES;
    _YearPickView.hidden = NO;
}

#pragma mark -
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{

    if (thePickerView == _monthPickView) {
        return 12;
    }else{
        return 16;
    }
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (thePickerView == _monthPickView) {
        return [_monthArray objectAtIndex:row];
    }else{
        return [_yearArray objectAtIndex:row];
    }

    
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (thePickerView == _monthPickView) {
        _monthPickView.hidden = YES;
        [_monthButton setTitle:_monthArray[row] forState:0];
        self.monthStr=_monthArray[row];
        [self.tableView reloadData];    }else{
            _YearPickView.hidden = YES;
            [_yearButton setTitle:_yearArray[row] forState:0];
            self.yearStr=_yearArray[row];
            [self.tableView reloadData];
        }

}

#pragma mark - Pay Now按钮点击事件
-(void)finishPayNow:(UIButton*)sender{
    NSString * currency = [[NSUserDefaults standardUserDefaults]valueForKey:@"CURRENCY"];
    if (sender.selected==YES) {
        return;
    }else{
        sender.selected=YES;
        [self performSelector:@selector(timeEnough:) withObject:nil afterDelay:2.0];
        NSString*str=[self judgeCansave];
        
        if (_canSave) {
            // http://viprunningonline.com/api/index.php?main_page=address_book_process
            
            NSString * aaa=@"main_page=checkout_confirmation";
            
            NSString * urlStr=[NSString stringWithFormat:@"%@%@",HTTP_ADDRESS,aaa];
            
            NSDictionary*params=@{@"Cp_Num":self.numberTextField.text,
                                  @"Cp_ExpireMonth":self.monthStr,
                                  @"Cp_ExpireYear":self.yearStr,
                                  @"Cp_CVV":self.CVVTextfield.text,
                                  @"zenid":[UserSession instance].cookie};
            HttpManager*manager=[[HttpManager alloc]init];
            
            [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
                
                NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
                
                if ([number isEqualToString:@"1"]) {
                    if (self.allPrice) {
                        //                facebook提交订单统计
                        [FBSDKAppEvents logEvent:@"PayOrder" parameters:@{@"currency":currency,@"money":self.allPrice,@"status":@"The payment information fill out successfully！"}];
                        
                        NSDictionary *dict = @{@"currency":[[NSUserDefaults standardUserDefaults]valueForKey:@"CURRENCY"],@"money":self.allPrice,@"status":@"The payment information fill out successfully！"};
                        [MobClick event:@"PayNowClick" attributes:dict];
                    }
                    [JRToast showWithText:@"The payment information fill out successfully！" duration: 2.0];
                    [self comeBackToRoot];
                }else{
                    if (self.allPrice) {
                        NSDictionary *dict =@{@"currency":currency,@"money":self.allPrice,@"status":data[@"status_message"]};
                        [MobClick event:@"PayNowClick" attributes:dict];
                        
                        [FBSDKAppEvents logEvent:@"PayOrder" parameters:@{@"currency":[[NSUserDefaults standardUserDefaults]valueForKey:@"CURRENCY"],@"money":self.allPrice,@"status":data[@"status_message"]}];
                    }
                    [JRToast showWithText:data[@"status_message"] duration:2.0];
                }
            }];
        }else{
            if (self.allPrice) {
                NSDictionary *dict = @{@"currency":currency,@"money":self.allPrice,@"index" : str};
                [MobClick event:@"PayNowClick" attributes:dict];
            }
            [JRToast showWithText:str duration:2.0];
        }
    }

}

-(void)timeEnough:(NSTimer*)timer{
    UIButton *btn=(UIButton*)[self.view viewWithTag:666];
    btn.selected=NO;
    [timer invalidate];
    timer=nil;
}

#pragma mark 未填写警告

-(NSString*)judgeCansave{
    _canSave=YES;
    
    if (_CVVTextfield.text.length==0) {
        _canSave=NO;
        return @"CVV cannot be empty！";
    }
    if (_numberTextField.text.length==0) {
        _canSave=NO;
        return @"Bank card number cannot be empty！";
    }
    if (_monthStr.length==0) {
        _canSave=NO;
        return @"Month cannot be empty！";
    }
    if (_yearStr.length==0) {
        _canSave=NO;
        return @"Year cannot be empty！";
    }
    
        return @"666";
}


#pragma mark 滚动tableview的时候收起键盘

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    _monthPickView.hidden = YES;
    _YearPickView.hidden = YES;
}



#pragma mark 键盘收回

-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
   [self.view endEditing:YES];
    _monthPickView.hidden = YES;
    _YearPickView.hidden = YES;
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
